package com.honey.compilation.sql.ddl;

import com.honey.compilation.sql.SqlConstraint;
import com.honey.compilation.sql.SqlKeyWord;
import com.honey.compilation.sql.ValueElement;
import com.honey.compilation.sql.dml.Condition;
import com.honey.core.builder.CharacterBuilder;
import com.honey.core.builder.CharacterBuilderFactory;
import com.honey.core.compiler.CompilationException;
import com.honey.core.compiler.IndentSpace;
import com.honey.core.utils.StringUtility;

/**
 * CHECK 约束. SQL 92 定义如下:<br />
 * &lt;check constraint definition&gt;    ::=   CHECK &lt;left paren&gt; &lt;search condition&gt; &lt;right paren&gt;
 * @author Administrator
 * 
 */
public class ConstraintCheck extends SqlConstraint {
	
	private ValueElement checkName ;
	
	private Condition condition = null;

	private static int index = 0;
	
	
	public ConstraintCheck(Condition condition) {
		this.condition = condition;

	}

	@Override
	public SQLConstraintType getSQLConstraintType() {
		return SQLConstraintType.CHECK;
	}

	@Override
	public CharacterBuilder compiledContent(int indentLevel) throws CompilationException {
		CharacterBuilder answer = CharacterBuilderFactory.createC16StringBuilder();
		if (condition != null) {
			//if( uniqueName == null){
				checkName = new ValueElement(
						CharacterBuilderFactory.createC16StringBuilder()
						.append(SqlKeyWord.OPERATION_UNDERSCORE)
						.append("ck").append(index)
						.append(SqlKeyWord.OPERATION_UNDERSCORE)
						.append( StringUtility.getRandomString(6) )
						.append(SqlKeyWord.OPERATION_UNDERSCORE).toString()
				);
				index ++ ;
			//}

			IndentSpace.spaceIndent(answer, indentLevel);
			answer.append(SqlKeyWord.CONSTRAINT )
			.append(checkName)
			.append(SqlKeyWord.CHECK)
			.append(SqlKeyWord.OPERATION_PAREN_LEFT)
			.append(condition.compiledContent(0))
			.append(SqlKeyWord.OPERATION_PAREN_RIGHT);
		}
		return answer;
	}

}
